<?php
namespace App\Http\Controllers\Api;
use App\V3\V3_1\Models\CheckModel;
use App\V3\V3_1\Models\OverflowBreakageChecksModel;
use App\V3\V3_1\Models\OverflowBreakageDetailModel;
use App\V3\V3_1\Models\OverflowBreakageModel;
use App\Services\OutInRepealService;
use Illuminate\Http\Request;
use Validator;
use Illuminate\Support\Facades\DB;

/**
 * 报溢报损
 * Class OverflowBreakageController
 * @package App\Http\Controllers\Api
 */
class OverflowBreakageController extends BaseController
{
    /**
     * 列表
     * change 在 2021/10/18 11:25 创建
     * @param Request $request
     */
    public function index(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
            'type'=>'required|integer',//类型：0-报溢 1-报损
            'repeal_status'=>'required|integer'//撤销状态：0-未撤销 1-已撤销
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = OverflowBreakageModel::select('*')
            ->where(['main_id'=>$this->getMainUserId(),'type'=>$data['type'],'repeal_status'=>$data['repeal_status']])
            ->whereIn('user_id',[$this->getMainUserId(),$this->getUserId()])
            ->orderBy('id','desc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        //响应
        foreach ($model as &$val){
            $val['goods_info'] = OverflowBreakageDetailModel::where(['o_b_main_id'=>$val['id']])->get();
            $val['check_info'] = OverflowBreakageChecksModel::select("id","name","mobile","status","refund_remark")->where(['o_b_main_id'=>$val['id']])->get();
        }
        return $this->success($model);
    }

    /**
     * 添加
     * change 在 2021/10/18 11:25 创建
     * @param Request $request
     */
    public function add(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'goods_info' =>'required|string',//商品信息  json array
            'proof_image' =>'string',//凭证图片(多图逗号分隔)
            'check_info' =>'required|string',//审批人信息 json array
            'type' =>'required|integer',//类型：0-报溢 1-报损

        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail($info);
        }

        //开启事务
        DB::beginTransaction();
        try{
            //报溢报损主单
            $mainInfo = [
                'main_id'=>$this->getMainUserId(),
                'user_id'=>$this->getUserId(),
                'type'=>$data['type'],
                'created_at'=>time()
            ];
            isset($data['proof_image'])?$mainInfo['proof_image'] = $data['proof_image']:'';
            //创建主单信息
            $mainId = OverflowBreakageModel::insertGetId($mainInfo);

            //商品详细添加
            $goodsInfo = json_decode($data['goods_info'],true);
            $remark = '';
            foreach ($goodsInfo as &$value){
                $value['main_id'] = $this->getMainUserId();
                $value['o_b_main_id'] = $mainId;
                $value['created_at'] = time();
                if(isset($value['remark']) && !empty($value['remark'])){
                    if(!$remark){
                        $remark = $value['remark'];
                    }else{
                        $remark = $remark.','.$value['remark'];
                    }
                }
            }
            OverflowBreakageDetailModel::insert($goodsInfo);
            //添加审批人
            $checkInfo = json_decode($data['check_info'],true);
            foreach ($checkInfo as &$val){
                $val['o_b_main_id'] = $mainId;
                $val['admin_id'] = $val['id'];
                $val['created_at'] = time();
                unset($val['id']);
            }
            OverflowBreakageChecksModel::insert($checkInfo);
            $checkPerson = OverflowBreakageChecksModel::where(['o_b_main_id'=>$mainId])->pluck('admin_id')->toArray();
            $checkPerson = implode(',',$checkPerson);
            CheckModel::insert([
                'type'=>$data['type'],
                'all_id'=>$mainId,
                'main_id'=>$this->getMainUserId(),
                'user_id'=>$this->getUserId(),
                'remark'=>$remark,
                'check_person'=>$checkPerson,
                'check_person_tmp'=>$checkPerson,
                'created_at'=>time(),
                'updated_at'=>time()

            ]);
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            if($data['type']==0){
                $msg = '添加报溢异常';
            }else{
                $msg = '添加报损异常';
            }
            //异常响应
            $this->fail($e->getMessage(),$msg);
        }
    }

    /**
     * 编辑
     * change 在 2021/10/18 11:26 创建
     * @param Request $request
     */
    public function edit(Request $request){


        return $this->success();
    }

    /**
     * 撤销
     * change 在 2021/10/18 11:26 创建
     * @param Request $request
     */
    public function repeal(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//报溢报损主单 主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail($info);
        }

        $res = OutInRepealService::repeal($data['id'],3);

        if($res==0){
            return $this->fail('','商品被删除，无法撤销');
        }
        if($res==1){
            return $this->success('','撤销成功');
        }
        if($res==2){
            return $this->fail('','库存数量不足，无法撤销');
        }
    }

    /**
     * 详细
     * change 在 2021/10/19 14:39 创建
     * @param Request $request
     */
    public function detail(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//报溢报损主单 主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail($info);
        }
        $model = OverflowBreakageModel::find($data['id']);
        $model['goods_info'] = OverflowBreakageDetailModel::where(['o_b_main_id'=>$model['id']])->get();
        $model['check_info'] = OverflowBreakageChecksModel::select("id","name","mobile","status","refund_remark")->where(['o_b_main_id'=>$model['id']])->get();
        return $this->success($model);
    }
}
